<?php
/**
 * Created by lzl
 * Date: 2021 2021/10/18
 * Time: 13:53
 */
namespace App\Plugins\Services\Api;

use App\Exceptions\RequestException;
use App\Forms\AddressForms;
use App\Forms\ConfigForms;
use App\Forms\GoodsAttributeForms;
use App\Forms\PluginForms;
use App\Forms\StockForms;
use App\Forms\UserForms;
use App\Models\ShareFreeOrder;
use App\Models\User;
use App\Plugins\Forms\ShareFreeForms;
use App\Plugins\Forms\ShareFreeOrderForms;

class ShareFreeOrderServices
{

    /**
     * 订单详情
     * @param $validated
     * @return array
     */
    public function generateOrder($validated)
    {

        $validated['uid'] = UID;

        $forms = new ShareFreeOrderForms();

        //邀请人进入订单
        if(isset($validated['order_id']) && $validated['order_id']){
            $order = $forms->getShareOrderDetail($validated['order_id'])->toArray();
            $order['is_helped'] = $forms->checkShareLog([
                'order_id' => $validated['order_id'],
                'uid' => UID,
            ]);
        }else{
            unset($validated['order_id']);
            $order = $forms->getOrCreateOrder($validated)->toArray();
        }


        return [
            'order' => $order,
            'log'   => $forms->getShareLog($order['id'] ?? 0),
            'plugin' => (new PluginForms())->getDetail('share_free'),
        ];
    }


    /**
     * 新增记录
     * @param $validated
     * @return int
     * @throws RequestException
     */
    public function dealShare($validated)
    {
        $form = new ShareFreeOrderForms();

        $order = $form->getShareOrderDetail($validated['order_id']);

        $user = (new UserForms())->getUserDetail(UID);

        $this->checkStatus($form, $order, $user);

        $validated['uid']       = UID;
        $validated['share_id']  = $order->share_id;
        $validated['avatar']    = $user->avatar;
        $validated['nick_name'] = $user->nick_name;

        $form->setShareLog($validated);

        //查看订单状态
        if(($order->now_numbers + 1) == $order->numbers){
            $form->updateShareOrder($validated['order_id'], ['status' => ShareFreeOrder::SUCCESS]);
        }

        return $form->incShareCount($validated['order_id']);

    }

    /**
     * 检查助力
     * @param ShareFreeOrderForms $form
     * @param ShareFreeOrder $order
     * @param User $user
     * @throws RequestException
     */
    public function checkStatus($form, $order, $user)
    {
        if(time() > strtotime($order->end_time)){
            throw new RequestException('当前助力商品已超时，助力失败');
        }

        if($form->checkShareLog(['uid' => UID])){ //当前用户已参与助力
            throw new RequestException('当前用户已参与助力，助力失败');
        }

        if($user->source != 'share_free'){ //检测渠道来源
            throw new RequestException('仅限现用户参与助力');
        }

        //判断当前用户上级是否为助力订单用户
        if($user->pid != $order->uid){
            throw new RequestException('助力用户上级异常，助力失败');
        }

        //todo  这里有也有并发问题隐患
        if($order->now_numbers >= $order->numbers){
            throw new RequestException('当前商品已助力成功，无需再次助力');
        }
    }




    /**
     * @return array
     */
    public function preview()
    {
        //快递信息
        $express = [
            'express_min'    => (new ConfigForms())->getDetail('express_min')->value,
            'express_amount' => (new ConfigForms())->getDetail('express_amount')->value,
        ];

        //收货地址
        $address = (new AddressForms())->addressDefault(UID);

        return compact('express', 'address');
    }


    /**
     * 下单
     * @param $order_id
     * @return array
     * @throws RequestException
     */
    public function confirmPreview($order_id)
    {
        $shareOrder = ShareFreeOrder::whereKey($order_id)->first();

        $attribute_form = new GoodsAttributeForms();

        $attribute = $attribute_form->getGoodsAttributeListSingle($shareOrder->goods_id);

        //库存判断
        (new StockForms())->compareStock($attribute, 1);

        $goods[0]['attribute_id'] = $attribute->id;
        $goods[0]['count'] = 1;

        //身份定价
        $goods[0]['detail'] = $attribute_form->getGoodsPreview($attribute, (new UserForms())->getUserDetail(UID));
        $goods[0]['detail']['pay_price'] = $shareOrder->amount;

        $shareOrder = $shareOrder->toArray();

        return array_merge(compact('goods','shareOrder'), $this->preview());

    }


    /**
     * @param $id
     * @return ShareFreeOrder|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function getOrder($id)
    {
        return (new ShareFreeOrderForms())->getShareOrderDetail($id);
    }


    /**
     * @param $id
     * @return bool|int
     * @throws RequestException
     */
    public function submitOrder($id)
    {
        //TODO 效验状态，以及助力人数
        $order = (new ShareFreeOrderForms())->getShareOrderDetail($id);

        if($order->status != ShareFreeOrder::SUCCESS){
            throw new RequestException('助力订单异常');
        }

        if((new ShareFreeOrderForms())->getShareLogCount($id) < $order->numbers){
            throw new RequestException('助力人数异常');
        }

        return $order->update([
            'status' => ShareFreeOrder::SUBMIT
        ]);
    }
}